<template>
  <div class="users-list">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ name: 'welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <!-- 添加用户--S -->
      <el-row :gutter="20">
        <el-col :span="9">
          <el-input
            placeholder="请输入内容"
            v-model="queryInfo.query"
            clearable
            @clear="getUserList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserList"
            ></el-button> </el-input
        ></el-col>
        <el-col :span="4"
          ><el-button type="primary" @click="addUserDialogVisible = true"
            >添加用户</el-button
          ></el-col
        >
      </el-row>
      <!-- 添加用户--E -->
      <!-- 用户列表--S -->
      <el-table :data="userList" border stripe style="width: 100%">
        <el-table-column type="index"> </el-table-column>
        <el-table-column prop="username" label="姓名" width="180">
        </el-table-column>
        <el-table-column prop="email" label="邮箱" width="180">
        </el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="userStateChange(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="getUserInfo(scope.row.id)"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="deleteUser(scope.row.id)"
            ></el-button>

            <el-tooltip
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="resetRole(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 添加列表--E -->
      <!-- 分页--S -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 3, 5]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
      <!-- 分页--E -->
    </el-card>
    <!-- 添加用户对话框--S -->
    <el-dialog
      title="添加用户"
      :visible.sync="addUserDialogVisible"
      width="50%"
      @close="resetAddUserForm"
    >
      <!-- 添加用户表单 -->
      <el-form
        :model="addUserForm"
        :rules="addUserRules"
        ref="addFormRef"
        label-width="80px"
      >
        <el-form-item label="用户名称" prop="username">
          <el-input v-model="addUserForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addUserForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addUserForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addUserForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addUserDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addNewUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加用户对话框--E -->
    <!-- 编辑用户对话框--S -->
    <el-dialog
      title="编辑用户"
      :visible.sync="editUserDialogVisible"
      width="50%"
      @close="resetEditUserForm"
    >
      <el-form
        :model="editUserForm"
        :rules="editUserRules"
        ref="editFormRef"
        label-width="80px"
      >
        <el-form-item label="用户名">
          <el-input v-model="editUserForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editUserForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editUserForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editUserDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑用户对话框--E -->
    <!-- 分配角色对话框--S -->
    <el-dialog
      title="提示"
      :visible.sync="resetRoleDialogVisible"
      @close="resetRoleDialog"
      width="50%"
    >
      <div>
        <p>当前的用户：{{ userInfo.username }}</p>
        <p>当前的角色：{{ userInfo.role_name }}</p>
        <p>
          添加新角色：
          <el-select v-model="selectedId" placeholder="请选择">
            <el-option
              v-for="item in userListRole"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="resetRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="resetRoleOnConfirm">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色对话框--E -->
  </div>
</template>

<script>
import {
  getUserListAPI,
  changeUserStateAPI,
  addUserAPI,
  getUserInfoByIdAPI,
  editUserInfoAPI,
  deleteUserByIdAPI,
  resetUserRolesAPI,
  getRolesListAPI
} from '@/api'
export default {
  name: 'UsersList',
  data() {
    // 校验邮箱
    const checkEmail = (rule, value, callback) => {
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (regEmail.test(value)) {
        callback()
      } else {
        callback(new Error('请输入合法邮箱'))
      }
    }
    // 校验手机
    const checkMobile = (rule, value, callback) => {
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (regMobile.test(value)) {
        callback()
      } else {
        callback(new Error('请输入合法手机号'))
      }
    }
    return {
      userList: [],
      userListRole: [],
      editUserForm: {},
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      total: 0,
      addUserDialogVisible: false,
      editUserDialogVisible: false,
      resetRoleDialogVisible: false,
      // 当前用户信息
      userInfo: {},
      selectedId: '',
      addUserForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 添加用户表单校验规则
      addUserRules: {
        username: [
          { required: true, message: '请输入用户名称', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 15, message: '长度在 3 到 15 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 编辑用户表单校验规则
      editUserRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    // 获取用户列表
    async getUserList() {
      try {
        const { data } = await getUserListAPI(this.queryInfo)
        // console.log(data)
        if (data.meta.status !== 200) {
          return this.$message.error('获取用户数据列表失败')
        }
        this.userList = data.data.users
        this.total = data.data.total
      } catch (err) {
        this.$message.error('获取用户数据列表失败')
      }
    },
    // 方框内显示每页条数
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`)
      this.queryInfo.pagesize = val
      this.getUserList()
    },
    // 点击哪一页的功能处理
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`)
      this.queryInfo.pagenum = val
      this.getUserList()
    },
    // 用户状态改变处理函数
    async userStateChange(userInfo) {
      try {
        const { data } = await changeUserStateAPI(
          userInfo.id,
          userInfo.mg_state
        )
        if (data.meta.status !== 200) {
          userInfo.mg_state = !userInfo.mg_state
          return this.$message.error('更新用户状态失败')
        }
        this.$message.success('更新用户状态成功')
        // console.log(data)
      } catch (err) {
        this.$message.error('更新用户状态失败')
      }
    },
    // 关闭对话框，重置增加用户的表单
    resetAddUserForm() {
      this.$refs.addFormRef.resetFields()
    },
    // 新增用户处理
    addNewUser() {
      // 表单预校验
      this.$refs.addFormRef.validate(async valid => {
        // console.log(valid)
        if (!valid) {
          return
        }
        try {
          // 校验通过，发请求，拿数据，渲染页面
          const { data } = await addUserAPI(this.addUserForm)
          // console.log(data)
          if (data.meta.status !== 201) {
            this.$message.error('增加用户失败')
          }
          this.$message.success('增加用户成功')
          this.addUserDialogVisible = false
          this.getUserList()
        } catch (err) {
          this.$message.error('增加用户失败')
        }
      })
    },
    // 获取用户信息
    async getUserInfo(id) {
      try {
        const { data } = await getUserInfoByIdAPI(id)
        // console.log(data)
        if (data.meta.status !== 200) {
          return this.$message.error('获取用户信息失败')
        }
        this.editUserForm = data.data
        this.$message.success('获取用户信息成功')
      } catch (err) {
        this.$message.error('获取用户信息失败')
      }
      this.editUserDialogVisible = true
    },
    // 关闭对话框，重置编辑用户的表单
    resetEditUserForm() {
      this.$refs.editFormRef.resetFields()
    },
    // 编辑用户信息
    async editUserInfo() {
      // 预校验
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        try {
          const { data } = await editUserInfoAPI(this.editUserForm.id, {
            email: this.editUserForm.email,
            mobile: this.editUserForm.mobile
          })
          if (data.meta.status !== 200) {
            return this.$message.error('编辑用户信息失败')
          }
          // 成功则关闭弹层，渲染页面,提示成功
          this.editUserDialogVisible = false
          this.$message.success('编辑用户信息成功')
          this.getUserList()
        } catch (err) {
          this.$message.error('编辑用户信息失败')
        }
      })
    },
    // 根据 id 删除用户
    async deleteUser(id) {
      // 弹窗提醒用户是否确认删除
      const res = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      if (res !== 'confirm') return this.$message.info('已取消删除该用户')
      // 请求接口，渲染页面，提示成功
      try {
        const { data } = await deleteUserByIdAPI(id)
        if (data.meta.status !== 200) return this.$message.error('删除用户失败')
        this.getUserList()
        this.$message.success('删除用户成功')
      } catch (err) {
        this.$message.error('删除用户失败')
      }
    },
    // 分配角色
    async resetRole(user) {
      this.userInfo = user
      try {
        const { data } = await getRolesListAPI()
        if (data.meta.status !== 200) {
          return this.$message.error('获取所有用户失败')
        }
        // console.log(data)
        this.userListRole = data.data
      } catch (err) {
        this.$message.error('获取所有用户失败')
      }
      this.resetRoleDialogVisible = true
    },
    // 重置角色分配弹框
    resetRoleDialog() {
      this.userInfo = {}
      this.selectedId = ''
    },
    // 点击确定分配角色
    async resetRoleOnConfirm() {
      if (!this.selectedId) {
        return this.$message.error('添加新角色必填项')
      }
      try {
        const { data } = await resetUserRolesAPI(
          this.userInfo.id,
          this.selectedId
        )
        if (data.meta.status !== 200) {
          return this.$message.error('分配角色失败')
        }
        // console.log(data)
        this.$message.success('分配角色成功')
        this.getUserList()
        this.resetRoleDialogVisible = false
      } catch (err) {
        this.$message.error('分配角色失败')
      }
    }
  }
}
</script>

<style scoped lang="less">
.users-list {
  .el-table {
    margin: 15px auto;
  }
}
</style>
